package aes.a2;

import java.io.*;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.*;


public class XmlUtils {

	public static Document createNewXMLDocument() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e1) {
			e1.printStackTrace();
		}
		return db.newDocument();
	}
	
	public static NodeList getNodeList(Node document, String xpathString) {
		try {
			return (NodeList) getXPath().evaluate(xpathString, document,
					XPathConstants.NODESET);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static javax.xml.xpath.XPath xPathObj = null;

	public static javax.xml.xpath.XPath getXPath() {
		if (xPathObj == null) {
			// 1. Instantiate an XPathFactory.
			javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory
					.newInstance();

			// 2. Use the XPathFactory to create a new XPath object
			xPathObj = factory.newXPath();
		}
		return xPathObj;
	}

	public static String printXML(Node doc) {
		// set up a transformer
		TransformerFactory transfac = TransformerFactory.newInstance();
		Transformer trans = null;
		try {
			trans = transfac.newTransformer();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
		trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		trans.setOutputProperty(OutputKeys.INDENT, "yes");

		// create string from xml tree
		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult(sw);
		DOMSource source = new DOMSource(doc);
		try {
			trans.transform(source, result);
		} catch (TransformerException e) {
			e.printStackTrace();
		}

		String xmlString = result.getWriter().toString();

		// print xml
		// System.out.println("Here's the xml:\n\n" + xmlString);

		return xmlString;
	}
}
